package com.ssy.lingxi.product.serviceImpl;

import cn.hutool.core.util.ObjectUtil;
import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.manage.api.model.vo.area.AreaVO;
import com.ssy.lingxi.product.api.model.request.warehouse.*;
import com.ssy.lingxi.product.api.model.response.warehouse.InvoicesTypeListResponse;
import com.ssy.lingxi.product.api.model.response.warehouse.WarehouseResponse;
import com.ssy.lingxi.product.entity.warehouse.InvoicesType;
import com.ssy.lingxi.product.entity.warehouse.Warehouse;
import com.ssy.lingxi.product.repository.warehouse.InvoicesRepository;
import com.ssy.lingxi.product.repository.warehouse.InvoicesTypeRepository;
import com.ssy.lingxi.product.service.InvoicesTypeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class InvoicesTypeServiceImpl implements InvoicesTypeService {

    @Resource
    InvoicesTypeRepository invoicesTypeRepository;

    @Resource
    InvoicesRepository invoicesRepository;

    /**
     * 查询单据类型列表
     *
     * @author wrc
     * @date 2020/6/22
     */
    @Override
    public Wrapper<PageData<InvoicesTypeListResponse>> invoicesTypeList(InvoicesTypeListRequest request, UserLoginCacheDTO sysUser) {
        String name = request.getName();
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        Pageable page = PageRequest.of(request.getCurrent() - 1, request.getPageSize());
        Page<InvoicesType> pageList;
        if(StringUtils.isNotBlank(name)){
            pageList = invoicesTypeRepository.findByMemberIdAndMemberRoleIdAndNameContainingOrderByUpdateTimeDesc(memberId, memberRoleId, name, page);
        }else{
            pageList = invoicesTypeRepository.findByMemberIdAndMemberRoleIdOrderByUpdateTimeDesc(memberId, memberRoleId, page);
        }
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(invoicesType -> {
            InvoicesTypeListResponse invoicesTypeListResponse = new InvoicesTypeListResponse();
            BeanUtils.copyProperties(invoicesType, invoicesTypeListResponse);
            return invoicesTypeListResponse;
        }).collect(Collectors.toList())));
    }

    /**
     * 查询单据类型详情
     *
     * @author wrc
     * @date 2020/8/6
     */
    @Override
    public Wrapper<InvoicesTypeListResponse> invoicesTypeDetails(Long id) {
        InvoicesType invoicesType = invoicesTypeRepository.findById(id).orElse(null);
        if(ObjectUtil.isNull(invoicesType)){
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        InvoicesTypeListResponse invoicesTypeListResponse = new InvoicesTypeListResponse();
        BeanUtils.copyProperties(invoicesType, invoicesTypeListResponse);
        return Wrapper.success(invoicesTypeListResponse);
    }

    /**
     * 删除单据类型
     *
     * @author wrc
     * @date 2020/6/22
     */
    @Transactional
    @Override
    public Wrapper<Void> invoicesTypeDelete(Long id) {
        InvoicesType invoicesType = invoicesTypeRepository.findById(id).orElse(null);
        if(ObjectUtil.isNull(invoicesType)){
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (!CommonConstant.State.STATE_STOP.equals(invoicesType.getState())) {
            return Wrapper.fail(ResponseCode.INCORRECT_DATA_STATE_CANNOT_BE_DELETED);
        }
        invoicesTypeRepository.deleteById(id);
        return Wrapper.success();
    }

    /**
     * 增加/修改单据类型
     *
     * @author wrc
     * @date 2020/6/22
     */
    @Transactional
    @Override
    public Wrapper<Void> invoicesTypeAddOrUpdate(InvoicesTypeAddOrUpdateRequest request, UserLoginCacheDTO sysUser) {
        InvoicesType invoicesType = new InvoicesType();
        if(ObjectUtil.isNotNull(request.getId())){
            invoicesType = invoicesTypeRepository.findById(request.getId()).orElse(null);
            if(ObjectUtil.isNull(invoicesType)){
                return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
            }
            if (!CommonConstant.State.STATE_STOP.equals(invoicesType.getState())) {
                return Wrapper.fail(ResponseCode.INCORRECT_DATA_STATE_CANNOT_BE_UPDATE);
            }
        }else{
            invoicesType.setCreateTime(System.currentTimeMillis());
            invoicesType.setNumber(getInvoicesTypeNo("LB"));
            invoicesType.setState(CommonConstant.State.STATE_START);
        }
        BeanUtils.copyProperties(request, invoicesType);
        invoicesType.setUpdateTime(System.currentTimeMillis());
        invoicesType.setMemberRoleId(sysUser.getMemberRoleId());
        invoicesType.setMemberId(sysUser.getMemberId());
        invoicesTypeRepository.saveAndFlush(invoicesType);
        return Wrapper.success();
    }

    /**
     * 生成单据类型编号
     *
     * @author wrc
     * @date 2020/9/12
     */
    private String getInvoicesTypeNo(String str) {
        StringBuilder strBuilder = new StringBuilder(str);
        for (int i = 0; i < 2; i++) {
            strBuilder.append((char) (Math.random() * 26 + 'a'));
        }
        str = strBuilder.toString();
        int number = (int) (Math.random() * 90000) + 10000;
        return str.toUpperCase() + number;
    }

    /**
     * 停用启用单据类型
     *
     * @author wrc
     * @date 2020/6/22
     */
    @Transactional
    @Override
    public Wrapper<Void> invoicesTypeStartOrStop(InvoicesTypeStateUpdateRequest request) {
        InvoicesType invoicesType = invoicesTypeRepository.findById(request.getId()).orElse(null);
        if(ObjectUtil.isNull(invoicesType)){
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (invoicesRepository.existsAllByInvoicesTypeId(invoicesType.getId())) {
            return Wrapper.fail(ResponseCode.INVOICES_CAN_T_STOP);
        }
        invoicesType.setUpdateTime(System.currentTimeMillis());
        invoicesType.setState(request.getState());
        invoicesTypeRepository.saveAndFlush(invoicesType);
        return Wrapper.success();
    }

    /**
     * 查询全部单据类型
     * @author wrc
     * @date 2020/8/5
     */
    @Override
    public Wrapper<List<InvoicesTypeListResponse>> invoicesTypeAll(UserLoginCacheDTO sysUser) {
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        List<InvoicesType> list = invoicesTypeRepository.findByMemberIdAndMemberRoleIdAndStateOrderByUpdateTimeDesc(memberId, memberRoleId, CommonConstant.State.STATE_START);
        return Wrapper.success(list.stream().map(invoicesType -> {
            InvoicesTypeListResponse invoicesTypeListResponse = new InvoicesTypeListResponse();
            BeanUtils.copyProperties(invoicesType, invoicesTypeListResponse);
            return invoicesTypeListResponse;
        }).collect(Collectors.toList()));
    }
}
